package cn.itcast.wanxinp2p.account.service.impl;

import cn.itcast.wanxinp2p.account.entity.Account;
import cn.itcast.wanxinp2p.account.mapper.AccountMapper;
import cn.itcast.wanxinp2p.account.service.AccountService;
import cn.itcast.wanxinp2p.account.service.SmsService;
import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: Liu
 * @date: 2022/03/25
 * @time: 12:11
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private SmsService smsService;

    @Override
    public RestResponse getSMSCode(String mobile) {
        return smsService.getSmsMessageCode(mobile);
    }

    @Override
    public RestResponse<Integer> checkMobile(String mobile, String key, String code) {
        //检查验证码
        smsService.verifySmsCode(key, code);

        //检查手机号
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getMobile, mobile);
        int count = this.count(wrapper);
        if (count > 0) {
            //用户存在,登录
            return RestResponse.success(1);
        } else {
            //用户不存在,注册
            return RestResponse.success(0);
        }
    }

    //AccountRegisterDTO 业务DTO,绑定特定业务,一般作为参数
    //AccountDTO 一般是返回值,做了脱敏处理
    @Override
    public AccountDTO register(AccountRegisterDTO registerDTO) {

        Account account = new Account();
        //获取用户数据保存到数据库
        /*account.setMobile(registerDTO.getMobile());
        account.setUsername(registerDTO.getUsername());
        account.setPassword(registerDTO.getPassword());*/

        BeanUtils.copyProperties(registerDTO,account);

        this.saveOrUpdate(account);

        //转换成AccountDTO返回  一般都是进行数据脱敏

        AccountDTO accountDTO = new AccountDTO();
/*        accountDTO.setMobile(registerDTO.getMobile());
        accountDTO.setUsername(registerDTO.getUsername());*/

        BeanUtils.copyProperties(account,accountDTO);


        return accountDTO;
    }
}
